package com.zhang.sequencegenerate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhang.sequencegenerate.entity.SequenceRecord;
import com.zhang.sequencegenerate.mapper.SequenceRecordMapper;
import com.zhang.sequencegenerate.service.SequenceRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description
 * @Author Mr.Zhang
 * @Date 2025/5/25 21:04
 * @Version 1.0
 */
@Service
public class SequenceRecordServiceImpl extends ServiceImpl<SequenceRecordMapper, SequenceRecord> implements SequenceRecordService {

    @Autowired
    private SequenceRecordMapper sequenceRecordMapper;

    /**
     * 查询序列
     *
     * @param sequenceKey
     * @return
     */
    @Override
    public SequenceRecord querySequence(String sequenceKey) {
        LambdaQueryWrapper<SequenceRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SequenceRecord::getSequenceKey, sequenceKey);
        SequenceRecord sequenceRecord = sequenceRecordMapper.selectOne(queryWrapper);
        if (sequenceRecord == null) {
            // 初始化
            initSequenceRecord(sequenceKey);
        }
        return sequenceRecordMapper.selectOne(queryWrapper);
    }

    /**
     * 采用乐观锁更新数据库序列值
     *
     * @param newValue
     * @param oldValue
     * @param sequenceKey
     * @return
     */
    @Override
    public int nextValue(long newValue, Long oldValue, String sequenceKey) {
        return sequenceRecordMapper.nextValue(newValue, oldValue, sequenceKey);
    }

    /**
     * 初始化序列
     *
     * @param sequenceName
     */
    private void initSequenceRecord(String sequenceKey) {
        SequenceRecord sequenceRecord = new SequenceRecord();
        sequenceRecord.setSequenceKey(sequenceKey);
        sequenceRecord.setSequenceValue(0L);
        sequenceRecordMapper.insert(sequenceRecord);
    }
}
